import {useState} from 'react';
import {Button, Form, Input, Modal} from 'antd';
import {updatePassword} from '@/services/usercenter.ts';
import useBaseFontSize from "@/hooks/useBaseFontSize.ts";
import ReadonlyPassword from "@/components/ReadonlyPassword";
import {getCurrentUser} from "@/utils/authority";

const ChangePasswordForm = (props: any) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const currentUser = getCurrentUser();
  const userId = currentUser.id;
  const layout = {
    labelCol: {span: 6},
    wrapperCol: {span: 18},
  };

  const checkConfirm = (_: any, value: any) => {
    const promise = Promise;
    if (value && value !== form.getFieldValue('newUserPassword')) {
      return promise.reject('两次输入的密码不一致');
    }
    return promise.resolve();
  };

  const onFinish = ({confirm, ...values}: any) => {
    const {onCancel} = props;
    setLoading(true);

    form.validateFields().then(() => {
      updatePassword(values).then(() => {
        if (onCancel) {
          onCancel();
        }
      });
    });
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };

  const baseFontSize = useBaseFontSize();


  return (
    <Modal
      destroyOnClose
      width={baseFontSize * 400}
      title="修改密码"
      centered={true}
      open={props.modalVisible}
      footer={[
        [
          <Button
            key="back"
            onClick={() => {
              props.onCancel();
            }}
          >
            取消
          </Button>,
          <Button
            key="submit"
            type="primary"
            loading={loading}
            onClick={() => {
              form.submit();
            }}
          >
            确定
          </Button>,
        ],
      ]}
      onOk={onFinish}
      onCancel={() => {
        props.onCancel();
      }}
    >
      <Form
        form={form}
        {...layout}
        onFinish={onFinish}
        initialValues={{
          id: userId
        }}
        onFinishFailed={onFinishFailed}
      >
        <Form.Item name="id" hidden>
          <Input/>
        </Form.Item>
        <Form.Item
          label="原始密码"
          name="oldUserPassword"
          rules={[{required: true, message: '请输入密码'}]}
        >
          <ReadonlyPassword/>
        </Form.Item>

        <Form.Item
          label="新密码"
          name="newUserPassword"
          rules={[{required: true, message: '请输入新密码'}]}
        >
          <ReadonlyPassword/>
        </Form.Item>

        <Form.Item
          label="确认密码"
          name="confirm"
          rules={[
            {required: true, message: '请再次输入新密码'},
            {validator: checkConfirm},
          ]}
        >
          <ReadonlyPassword/>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default ChangePasswordForm;
